<template>
	<div class="editor-main">
		<!-- 工具栏 -->
		<Toolbar :editor="editorRef" :mode="mode" style="border-bottom: 1px solid #dfe2e8" />
		<!-- 编辑器 -->
		<Editor
			:model-value="modelValue"
			:style="style"
			:disabled="disabled"
			:default-config="editorConfig"
			:mode="mode"
			@on-created="handleCreated"
			@on-change="handleChange"
		/>
		<div class="word-limit">
			内容限制：(<span :style="limitStyle">{{ wordLimit }}</span
			>/100) %
		</div>
	</div>
</template>

<style scoped>
.editor-main {
	border-width: 1px;
	border-style: solid;
	border-color: rgba(228, 228, 228, 1);
	border-radius: 4px;
	background-color: #fff;
	z-index: 100;
	width: 100%;
}
.editor-main:focus-within {
	border-color: #409eff;
}
.word-limit {
	text-align: right;
	padding: 10px;

	height: 20px;
	border-top: 1px solid #dfe2e8;
}
</style>

<script lang="ts" setup>
import '@wangeditor/editor/dist/css/style.css'
import { onBeforeUnmount, ref, shallowRef } from 'vue'
import constant from '@/utils/constant'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { IDomEditor, IEditorConfig } from '@wangeditor/editor'

const props = defineProps({
	modelValue: {
		type: String,
		required: true
	},
	mode: {
		type: String,
		default: 'default' // 可选值：[default | simple]
	},
	placeholder: {
		type: String,
		default: ''
	},
	style: {
		type: String,
		default: 'height: 400px;border:2px solid #f3f3f3;color: black;'
	},
	disabled: {
		type: Boolean,
		default: false
	}
})

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

type InsertFnType = (url: string, alt: string, href: string) => void

// 编辑器配置
const editorConfig: Partial<IEditorConfig> = {
	placeholder: props.placeholder,
	readOnly: props.disabled,
	MENU_CONF: {
		uploadImage: {
			server: constant.uploadUrl,
			fieldName: 'file',
			// 自定义插入图片
			customInsert(res: any, insertFn: InsertFnType) {
				// res 即服务端的返回结果
				// 从 res 中找到 url alt href ，然后插图图片
				insertFn(res.data.url, res.data.name, '')
			}
		}
	}
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
	const editor = editorRef.value
	if (editor == null) {
		return
	}
	editor.destroy()
})

const handleCreated = (editor: IDomEditor) => {
	editorRef.value = editor
}

//限制最大字符量
let maxWords = 1000
//限制百分比
let percent = maxWords / 100

// 编辑器change事件触发
const emit = defineEmits(['update:modelValue'])
const handleChange = (editor: IDomEditor) => {
	if (editor.getHtml() === '<p><br></p>') {
		wordLimit.value = 0
		return
	}

	wordLimit.value = editor.getHtml().length / percent

	if (wordLimit.value > 100) {
		style.value = 'height: 400px;border: 2px solid red;'
		limitStyle.value = 'color: red;font-size: 20px;'
	} else {
		style.value = props.style
		limitStyle.value = ''
		emit('update:modelValue', editor.getHtml())
	}
}

const style = ref(props.style)
const wordLimit = ref(0)
const limitStyle = ref()
</script>
